<template>
  <form-item-wrapper
    :designer="designer"
    :field="field"
    :rules="rules"
    :design-state="designState"
    :parent-id="parentId"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
  >
    <div v-if="previewStatus" class="inner_value" v-html="formData[fieldId]" />
    <vue-editor
      v-else
      ref="fieldEditor"
      v-model="formData[fieldId]"
      :editor-toolbar="customToolbar"
      :disabled="field.options.disabled"
      :placeholder="field.options.placeholder"
      @text-change="handleRichEditorChangeEvent"
      @focus="handleRichEditorFocusEvent"
      @blur="handleRichEditorBlurEvent"
    />
  </form-item-wrapper>
</template>

<script>
/* eslint-disable vue/require-default-prop */
/* eslint-disable eol-last */
import FormItemWrapper from "./form-item-wrapper";
import { VueEditor } from "vue2-editor";
import emitter from "Yan/utils/emitter";
import i18n from "Yan/utils/i18n";
import { deepClone } from "Yan/utils/util";
import fieldMixin from "./fieldMixin";

export default {
  name: "rich-editor_unit",
  componentName: "FieldWidget",
  components: {
    FormItemWrapper,
    VueEditor,
  },
  mixins: [emitter, fieldMixin, i18n],
  props: {
    designer: Object,
    fieldId: String,
    parentId: String,
    parentList: Array,
    indexOfParentList: Number,
    formData: Object,
    designState: {
      type: Boolean,
      default: false,
    },
  },
  // inject: ['refList', 'formConfig', 'globalOptionData', 'globalModel'],
  data() {
    return {
      oldFieldValue: null, // field组件change之前的值
      // fieldModel: null,
      rules: [],

      customToolbar: [], // 富文本编辑器自定义工具栏
      valueChangedFlag: false, // vue2-editor数据值是否改变标志
    };
  },
  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
         需要在父组件created中初始化！！ */
    // this.initFieldModel();
    // this.registerToRefList()
    this.initEventHandler();
    this.buildFieldRules();

    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
  },

  methods: {
    handleRichEditorChangeEvent() {
      this.valueChangedFlag = true;
      this.syncUpdateFormModel(this.fieldModel);
    },

    handleRichEditorFocusEvent() {
      this.oldFieldValue = deepClone(this.fieldModel);
    },

    handleRichEditorBlurEvent() {
      if (this.valueChangedFlag) {
        this.emitFieldDataChange(this.fieldModel, this.oldFieldValue);
        this.valueChangedFlag = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../../styles/global.scss"; //* form-item-wrapper已引入，还需要重复引入吗？ *//

.full-width-input {
  width: 100% !important;
}
</style>
